package com.eight.common.core.ibatis;

import com.eight.common.utils.enumeration.EnumFinder;
import com.eight.common.utils.enumeration.Enumerable;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({Enumerable.class})
public class IbatisEnumerableHandler<E extends Enumerable<K>, K> extends BaseTypeHandler<E> {
    private final Class<E> type;

    public IbatisEnumerableHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.type = type;
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        if (jdbcType == null) {
            ps.setString(i, String.valueOf(parameter.value()));
        } else {
            ps.setObject(i, parameter.value(), jdbcType.TYPE_CODE);
        }

    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (E) ObjectUtils.defaultIfNull(this.getByValue(this.type, rs.getObject(columnName)), (Object)null);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (E) ObjectUtils.defaultIfNull(this.getByValue(this.type, rs.getObject(columnIndex)), (Object)null);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (E) ObjectUtils.defaultIfNull(this.getByValue(this.type, cs.getObject(columnIndex)), (Object)null);
    }

    private E getByValue(Class<E> enumCls, Object value) {
        return (E) EnumFinder.findByValue(enumCls.asSubclass(Enum.class), value);
    }
}